package com.lyh.springJDBC.dao;

import com.lyh.springJDBC.model.User;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by Admin on 2017/10/31.
 */
@Repository("userDao")
public class UserDaoImpl implements UserDao {

    private JdbcTemplate jdbcTemplate;

    @Resource
    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    @Override
    public void add(User user) {
        this.jdbcTemplate.update(
                "insert into user (name, password,nickname) values (?,?,?)",
                user.getUsername(), user.getPassword(), user.getNickname());
    }

    @Override
    public void update(User user) {
        this.jdbcTemplate.update("update user set name = ?,password=?,nickname=?  where id = ?",
                user.getUsername(), user.getPassword(), user.getNickname(), user.getId());
    }

    @Override
    public void delete(int id) {
        this.jdbcTemplate.update("delete from user where id = ?", id);
    }

    @Override
    public User load(int id) {
      User user =  this.jdbcTemplate.queryForObject("select * from user where id=?", new Object[]{id},
              new RowMapper<User>() {
                  @Override
                  public User mapRow(ResultSet resultSet, int i) throws SQLException {
                      User user1 = new User();
                      user1.setId(resultSet.getInt(1));
                      user1.setUsername(resultSet.getString(2));
                      user1.setPassword(resultSet.getString(3));
                      user1.setNickname(resultSet.getString(4));
                      return user1;
                  }
              });
        return user;
    }

    @Override
    public List<User> list() {
        return this.jdbcTemplate.query("select * from user", new RowMapper<User>() {
            @Override
            public User mapRow(ResultSet resultSet, int i) throws SQLException {
                User user2 = new User();
                user2.setId(resultSet.getInt(1));
                user2.setUsername(resultSet.getString(2));
                user2.setPassword(resultSet.getString(3));
                user2.setNickname(resultSet.getString(4));
                return user2;
            }
        });
    }
}
